<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        :breadCrumb="['人事', '人事管理', '配置离职手续']"
        title="配置离职手续"
        :showBack="true"
      ></pageHeaderNew>
    </template>
    <div class="main">
      <!-- <div class="hear">
        <a-steps changeable :current="current" @change="setCurrent">
          <a-step description="">手续基础信息 </a-step>
          <a-step description="">编辑手续内容 </a-step>
          <a-step description="">确认发起 </a-step>
        </a-steps>
      </div> -->
      <div class="business">
        <a-form
          style="width: 100%"
          ref="formRef"
          :model="form.data"
          auto-label-width
          :rules="rules"
        >
          <!-- <a-form-item field="userName" label="离职人员：" required>
            <a-input v-model="form.data.userName" disabled />
          </a-form-item>
          <a-form-item field="name" label="离职手续名称：">
            <a-input v-model="form.data.name" placeholder="请输入" />
          </a-form-item> -->
          <a-form-item required field="templateId" label="选择离职手续模板：">
            <a-select
              placeholder="请选择"
              @change="(e)=>templatechange(e as number)"
              :options="SelectOption"
              v-model="form.data.templateId"
              :style="{ width: '320px' }"
            >
            </a-select>
          </a-form-item>
          <!-- <a-form-item label="离职手续描述：">
            <a-textarea
              v-model="form.data.remark"
              placeholder="请输入"
              style="height: 200px"
              allow-clear
            />
          </a-form-item> -->
        </a-form>
      </div>
      <div>
        <a-layout class="layout">
          <a-layout-header class="header">
            <div>
              <span></span>
              基础信息
            </div>
          </a-layout-header>
          <a-layout-content class="main">
            <div style="display: flex; justify-content: center">
              <div class="cn">
                <div
                  class="cn-main"
                  v-for="item in form.data.controls"
                  :key="item.ctlCode"
                >
                  <FormItem
                    v-if="item.ctlComponentType"
                    :disabled="true"
                    :code="item.ctlCode"
                    :componentType="item.ctlComponentType"
                    :required="item.ctlRequired"
                    :props="''"
                    :name="item.ctlCnName"
                    v-model:values="item.ctlValue"
                  />
                  <!-- <span>{{
                    item.ctlCnName ? item.ctlCnName : item.cnName + ':'
                  }}</span> -->
                  <!-- <a-input class="cn-input" disabled placeholder="自动获取" /> -->
                </div>
              </div>
            </div>
          </a-layout-content>
        </a-layout>
        <a-layout class="layout">
          <a-layout-header class="header">
            <div>
              <span></span>
              入职手续清单
            </div>
            <!-- <a-button @click="visibleEvent = true" type="primary"
              >新增</a-button
            > -->
          </a-layout-header>
          <a-layout-content class="main">
            <a-table
              :data="form.data.details"
              :span-method="dataSpanMethod"
              :bordered="{
                wrapper: true,
                cell: true,
                headerCell: true,
                bodyCell: true
              }"
              stripe
              :pagination="false"
            >
              <template #columns>
                <a-table-column
                  align="center"
                  title="办理环节"
                  dataIndex="handlerProcess"
                  :width="200"
                >
                </a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="handlerMatters"
                  align="center"
                  title="办理事项"
                ></a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="matterAsk"
                  align="center"
                  title="办理事项要求"
                ></a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="handlerDept"
                  align="center"
                  title="办理部门"
                >
                  <!-- <template #cell="{ record }">
                    <a-select
                      @change="(e)=>change(e as number,record,1)"
                      v-model="record.department"
                      :field-names="{ value: 'id', label: 'value' }"
                      :options="departmentSelectData.data"
                      :style="{ width: '100px' }"
                    >
                    </a-select>
                  </template> -->
                  <template #cell="{ record }">
                    {{
                      departmentSelectData.data.filter(
                        (ele: any) => ele.id === record.handlerDept
                      )[0]?.name
                    }}
                  </template>
                </a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="handlerUser"
                  align="center"
                  title="办理人"
                >
                  <template #cell="{ record }">
                    <!-- <a-select
                      @change="(e)=>change(e as number,record,2)"
                      v-model="record.person"
                      :field-names="{ value: 'id', label: 'name' }"
                      :options="agentSelectData.data"
                      :style="{ width: '100px' }"
                    >
                    </a-select> -->
                    {{ getRoster(record.handlerUser) }}
                  </template>
                </a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="userMobile"
                  align="center"
                  title="办理人联系方式"
                >
                  <template #cell="{ record }">
                    {{ record.userMobile || '自动获取' }}
                  </template>
                </a-table-column>
                <a-table-column
                  :width="200"
                  dataIndex="handlerAddr"
                  align="center"
                  title="办理地点"
                >
                  <!-- <template #cell="{ record }">
                    <a-select
                      @change="(e)=>change(e as number,record,3)"
                      v-model="record.handlerAddr"
                      :field-names="{ value: 'id', label: 'name' }"
                      :options="locationSelect.data"
                      :style="{ width: '100px' }"
                    >
                    </a-select>
                  </template> -->
                  <template #cell="{ record }">
                    {{
                      locationSelect.data.filter(
                        (ele: any) => ele.id === record.handlerAddr
                      )[0]?.name
                    }}
                  </template>
                </a-table-column>
                <a-table-column
                  title="操作"
                  dataIndex="operation"
                  align="center"
                  :width="120"
                  fixed="right"
                >
                  <template #cell="{ record, rowIndex }">
                    <a-tooltip content="编辑">
                      <icon-font
                        @click="edit(record)"
                        type="icon-edit"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-tooltip>
                    <a-tooltip content="删除" position="left">
                      <a-popconfirm
                        content="是否确认删除该条数据?"
                        @ok="del(record, rowIndex)"
                      >
                        <icon-font
                          type="icon-delete"
                          :size="26"
                          :style="{
                            cursor: 'pointer',
                            marginRight: '10px'
                          }"
                        />
                      </a-popconfirm>
                    </a-tooltip>
                  </template>
                </a-table-column>
              </template>
            </a-table>
            <div
              @click="addList"
              style="padding: 20px; color: #3d7eff; cursor: pointer"
            >
              <icon-plus /> 新增离职手续清单
            </div>
          </a-layout-content>
        </a-layout>
      </div>
      <!-- <div v-show="current === 3" :style="{ width: '50%', margin: 'auto' }">
        <a-form :model="form.data" auto-label-width>
          <a-form-item field="userName" label="入职人员：" required>
            <div class="avatar">
              <a-avatar :style="{ backgroundColor: '#b8d4ff' }">
                <IconUser :style="{ color: '#fff' }" />
              </a-avatar>
              <p>{{ form.data.userName }}</p>
            </div>
            <a-input v-model="form.data.userName" />
          </a-form-item>
          <a-form-item field="agents" label="办理人员：" required>
            <template v-if="person.length !== 0">
              <div class="avatar" v-for="item in person" :key="item">
                <a-avatar
                  v-if="item.handlerUser"
                  :style="{ backgroundColor: '#b8d4ff' }"
                >
                  <IconUser
                    v-if="item.handlerUser"
                    :style="{ color: '#fff' }"
                  />
                </a-avatar>
                <p v-if="item.handlerUser">
                  {{ getRoster(item.handlerUser) }}
                </p>
              </div>
            </template>
            <template v-else> 暂无 </template>
            <a-input v-model="form.data.agents" />
          </a-form-item>
          <a-form-item field="name" label="入职手续名称：" required>
            <a-input v-model="form.data.name" />
          </a-form-item>
        </a-form>
      </div> -->
    </div>
    <footer>
      <a-space>
        <!-- <a-button
          v-show="current === 2 || current === 3"
          @click="current = --current"
          class="btn"
          >上一步</a-button
        >
        <a-button
          type="primary"
          v-show="current === 1 || current === 2"
          @click="next"
          class="btn"
          >下一步</a-button
        > -->
        <a-button @click="router.back()" class="btn">取消</a-button>
        <a-button type="primary" @click="save" class="btn">保存</a-button>
        <a-button type="primary" @click="submit" class="btn">确认发起</a-button>
        <!-- <a-button v-show="current === 3" @click="current = 1" class="btn"
          >跳到基本信息</a-button
        > -->
      </a-space>
    </footer>
  </ContentCard>

  <eventFrom
    @updateFromData="updateFromData"
    @updateFromDataOne="updateFromDataOne"
    v-model:visible="visibleEvent"
    :fromData="editfromData"
    :allNode="allNode"
  />
</template>
<script setup lang="ts">
import FormItem from '@/components/DynamicFormsNew/RenderingForm/FormItem/index.vue';
import eventFrom from '@/views/Management/Human/BaseSetting/TransactionSetting/EntryFormalities/formalitiesTemplate/fromSetting/eventFrom';
import { findLastIndex } from 'lodash';

import clonedeep from 'lodash.clonedeep';
import { GetWorkPlaceList } from '@/apis/management/organization/organizationManagement';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import { flatTree } from '@/utils/utils';
import { GetHumanRosterList } from '@/apis/management/human/humanRoster';
import {
  PostEntryProcedure,
  PutEntryProcedure,
  GetEntryProcedureDetail
} from '@/apis/management/human/humanChange/entry/index';
import { PutLeaveProcedureStatus2Human } from '@/apis/management/human/humanChange/leave/index';
import {
  GetEntryScheme,
  GetEntrySchemeById,
  GetStaffDetails,
  GetOnboardingProcedure,
  GetOnboardingProcedureById,
  GetonboardingById,
  GetlistData,
  GetProcedureList
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  getOrganizationDetailById,
  getPositionDetailById
} from '@/utils/common';
import { useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
const visibleEvent = ref(false);
const router = useRouter();
const onboardingId = router.currentRoute.value.query.id;
const userId = router.currentRoute.value.query.id as unknown as number;
const current = ref(1);
const setCurrent = (index: number) => {
  current.value = index;
};
const form: any = reactive({
  data: {
    onboardingId: onboardingId,
    name: '',
    remark: '',
    userName: '',
    controls: [],
    details: [],
    agents: [],
    templateId: undefined,
    templateName: ''
  }
});
const allNode = computed(() => {
  const data: string[] = [];
  form.data.details?.forEach((ele: any) => {
    data.push(ele.node);
  });
  return data;
});
const rules = {
  name: [
    {
      required: true,
      message: '请输入入职手续名称'
    }
  ],
  templateId: [
    {
      required: true,
      message: '请选择离职手续模板'
    }
  ]
};

const getData = async (resData: any) => {
  try {
    const res = await GetEntryProcedureDetail({
      id: +userId,
      type: 3
    });

    if (res.id) {
      form.data = res;
      form.data.details = res.children;
      form.data.userName = resData.name;
    }
    const res2: any = await GetOnboardingProcedureById({
      id: form.data.templateId
    });
    form.data.controls = res2.collectionModel[0].controlModel;
    if (Array.isArray(form.data.controls) && form.data.controls.length !== 0) {
      form.data.controls?.forEach((ele: any) => {
        const index = humanInfoControl.findIndex(
          (item) => item.ctlCode === ele.ctlCode
        );
        ele.ctlValue = humanInfoControl[index]?.ctlValue?.ctlValue;
      });
      // for (let ele of form.data.controls) {
      //   const index = list.findIndex((item) => item.ctlCode === ele.ctlCode);
      //   ele.ctlValue = list[index]?.ctlValue?.ctlValue;
      //   // if (ele.ctlCode === 'CED44AC9966904CD1AB546D309903727C') {
      //   //   const res = await getOrganizationDetailById(+ele.ctlValue);

      //   //   ele.ctlValue = res.name;
      //   // } else if (ele.ctlCode === 'C7341027925C943708F3AEF98703ECC47') {
      //   //   const res = await getPositionDetailById(+ele.ctlValue);
      //   //   ele.ctlValue = res.name;
      //   // }
      // }
    }
    console.log(
      'getData',
      resData.useTemplate.collectionModel[0].controlModel,
      res
    );
  } catch (error: unknown) {
    console.log(error);
  }
};

const change = (e: number, data: any, type: number) => {
  form.data.details.forEach((ele: any) => {
    if (data.did === ele.id) {
      if (type === 1) {
        ele.department = e;
      } else if (type === 2) {
        ele.person = e;
      } else {
        ele.handlerAddr = e;
      }
    }
  });
};
const next = async () => {
  if (current.value === 1) {
    if (await formRef.value.validate()) {
      return Message.error('请填写必填项');
    }
  }

  current.value++;
};
const formRef = ref();
const editfromData = ref();
// 表格合并
const dataSpanMethod = (datas: any) => {
  const { record, rowIndex, columnIndex, column } = datas;
  // 当检索到相同数据则返回 那条数据
  let arr = form.data.details.filter((res: any) => {
    return res.handlerProcess == record.handlerProcess;
  });
  // 匹配到相同数据的长度
  // obj.rowspan = arr.length;
  if (
    form.data.details[rowIndex - 1]?.handlerProcess != record.handlerProcess &&
    (column.dataIndex === 'handlerProcess' ||
      column.dataIndex === 'handlerDept' ||
      column.dataIndex === 'handlerUser' ||
      column.dataIndex === 'handlerAddr' ||
      column.dataIndex === 'userMobile' ||
      column.dataIndex === 'operation' ||
      column.dataIndex === 'personName')
  ) {
    // 匹配到相同数据的长度
    return { rowspan: arr.length };
  }
};

const templatechange = async (e: number) => {
  const res: any = await GetOnboardingProcedureById({ id: e });
  const resp = await GetProcedureList({
    ownerId: e,
    ownerType: 3
  });
  form.data.controls = res.collectionModel[0].controlModel;
  form.data.details = resp.proceduresList || [];
  form.data.details.sort((a: any, b: any) =>
    a.handlerProcess.localeCompare(b.handlerProcess)
  );
  form.data.templateName = res.name;
  if (Array.isArray(form.data.controls) && form.data.controls.length !== 0) {
    form.data.controls?.forEach((ele: any) => {
      ele.ctlCode;
      const index = humanInfoControl.value.findIndex(
        (item) => item.ctlCode === ele.ctlCode
      );
      ele.ctlValue = humanInfoControl.value[index]?.ctlValue?.ctlValue;
    });
  }
};
const getRoster = (id: number) => {
  let s = '';
  s = agentSelectData.data?.filter((ele: any) => ele.id === id)[0]?.name;
  if (s) return s;
  return '未选择';
};
const visible = ref(false);

let humanInfoControl = ref(); // 保存人员控件信息
const init = async () => {
  const { content } = (await GetWorkPlaceList({
    pageNumber: 0,
    pageSize: -1
  })) as any;
  locationSelect.data = content;
  const Getlist: any = await GetOrganizationList({});
  departmentSelectData.data = flatTree(Getlist);
  const list = await GetHumanRosterList({
    pageNumber: 0,
    pageSize: -1,
    typeName: '1,2,3,4,5,6,7,8,9,10,11,12'
  });
  agentSelectData.data = list.content;
  const resData: any = await GetStaffDetails({
    id: +userId
  });
  humanInfoControl.value = resData.useTemplate.collectionModel[0].controlModel;
  form.data.userName = resData.name;

  const res: any = await GetOnboardingProcedure({
    pageNumber: 0,
    pageSize: -1,
    ownerType: 3
  });
  res.content?.forEach((ele: any) => {
    if (ele.enable === 1) SelectOption.push({ value: ele.id, label: ele.name });
  });
  getData(resData);
};
// 初始化默认模板
const initControlsdata = async () => {
  const res: any = await GetEntryScheme({ required: 1 });
  seconds.value = (await GetEntrySchemeById({
    id: res.content[0].id
  })) as any[];
};
// initControlsdata();

const person = computed(() => {
  if (
    Array.isArray(form.data.details) &&
    form.data.details.length !== 0 &&
    form.data.details[0].handlerUser
  ) {
    return form.data.details.filter((ele: any, index: any, arr: any) => {
      return (
        arr.map((ele: any) => ele.handlerUser).indexOf(ele.handlerUser) ===
        index
      );
    });
  } else {
    return [];
  }
});

const del = (data: any, inds: number) => {
  // let index = 0;
  // form.data.details.forEach((ele: any, ind: any) => {
  //   if (ele.id === data.id) {
  //     index = ind;
  //   }
  // });
  // form.data.details.splice(index, 1);

  // 找到所有环节相同的项
  form.data.details.forEach((item: any) => {
    if (item.id && item.handlerProcess === data.handlerProcess) {
      delIds.value.push(item.id);
    }
  });
  // 过滤删除项
  form.data.details = form.data.details.filter(
    (item: any) => item.handlerProcess !== data.handlerProcess
  );
};

const edit = (data: any) => {
  console.log('====================================');
  console.log(data);
  console.log('====================================');
  visibleEvent.value = true;
  const demands: any[] = [];
  form.data.details.forEach((item: any) => {
    if (item.handlerProcess === data.handlerProcess) {
      demands.push({
        id: item.id,
        handlerMatters: item.handlerMatters,
        matterAsk: item.matterAsk
      });
    }
  });
  const newData = clonedeep(data);
  newData.demands = demands;
  data.hid = form.data.id;
  newData.edit = true;
  editfromData.value = newData;
};

// const updateFromData = (e: any) => {
//   form.data.details.push(e);
// };
// const updateFromDataOne = (e: any) => {
//   // console.log(fromData.data);
//   let index = 0;
//   form.data.details.forEach((ele: any, ind: number) => {
//     console.log('ele', ele, e);
//     if (ele.id === e.did) {
//       index = ind;
//     }
//   });

//   form.data.details[index] = e;
//   console.log('index', index, form.data.details);
//   // fromData.data.push(e);
//   // emit('updateMaterialData', clonedeep(e));
// };

const seconds = ref();
const SelectOption: any = reactive([]);
const departmentSelectData: any = reactive({ data: [] }); // 部门
const agentSelectData: any = reactive({
  data: []
}); // 办理人
const locationSelect: any = reactive({ data: [] }); // 地点

const save = async () => {
  const data = {
    name: form.data.name,
    userId: +userId,
    userName: form.data.userName,
    templateId: form.data.templateId,
    remark: form.data.remark,
    children: clonedeep(form.data.details),
    status: 1,
    type: 3 // 离职默认传3
  };
  if (form.data.id) {
    data.id = form.data.id;
    await PutEntryProcedure(data);
    await PutLeaveProcedureStatus2Human({
      id: +userId,
      status: 1
    });
  } else {
    data.children.forEach((ele: any) => delete ele.id);
    await PostEntryProcedure(data);
    await PutLeaveProcedureStatus2Human({
      id: +userId,
      status: 1
    });
  }
  Message.success('提交成功');
  router.back();
};
const submit = async () => {
  const data = {
    name: form.data.name,
    userId: +userId,
    userName: form.data.userName,
    templateId: form.data.templateId,
    remark: form.data.remark,
    children: clonedeep(form.data.details),
    status: 2,
    type: 3 // 离职默认传3
  };
  if (form.data.id) {
    data.id = form.data.id;
    await PutEntryProcedure(data);
    await PutLeaveProcedureStatus2Human({
      id: +userId,
      status: 2
    });
  } else {
    data.children.forEach((ele: any) => delete ele.id);
    await PostEntryProcedure(data);
    await PutLeaveProcedureStatus2Human({
      id: +userId,
      status: 2
    });
  }
  Message.success('提交成功');
  router.back();
};
init();
const updateFromData = (e: any) => {
  if (typeof e.demands === 'object' && e.demands.length) {
    e.demands.forEach((item: any) => {
      console.log('item', item);

      const temp = Object.assign(item, e);
      form.data.details.push(temp);
    });
  }
  form.data.details.sort((a: any, b: any) =>
    a.handlerProcess.localeCompare(b.handlerProcess)
  );
};
const delIds = ref([]);
const updateFromDataOne = (e: any) => {
  form.data.details = form.data.details.filter(
    (item: any) =>
      item.handlerProcess !== editfromData.value.handlerProcess || item.id
  );

  if (typeof e.demands === 'object' && e.demands.length) {
    e.demands.forEach((item: any) => {
      if (!item.id) {
        const lastIndex = findLastIndex(
          form.data.details,
          (item: any) =>
            editfromData.value.handlerProcess === item.handlerProcess
        );
        //add
        item.ownerId = form.data.id;
        item.handlerProcess = e.handlerProcess;
        item.ownerType = 2;
        item.handlerDept = e.handlerDept;
        item.handlerUser = e.handlerUser;
        item.handlerAddr = e.handlerAddr;
        // procedure.list.push(item);
        console.log('item11', item);

        form.data.details.splice(lastIndex + 1, 0, item);
      } else {
        //edit
        const node = form.data.details.find((ele: any) => ele.id === item.id);
        if (!node) return;
        node.handlerMatters = item.handlerMatters;
        node.matterAsk = item.matterAsk;
        node.handlerProcess = e.handlerProcess;
        node.handlerDept = e.handlerDept;
        node.handlerUser = e.handlerUser;
        node.handlerAddr = e.handlerAddr;
      }
    });
  }
  //delete

  editfromData.value.demands?.forEach((pro: any) => {
    const index = e.demands.findIndex((demand: any) => pro.id === demand.id);
    if (index >= 0) return;
    const procedureIndex = form.data.details.findIndex(
      (item: any) => pro.id === item.id
    );
    if (procedureIndex >= 0) {
      form.data.details.splice(procedureIndex, 1);
    }

    delIds.value.push(pro.id);
  });
  form.data.details.sort((a: any, b: any) =>
    a.handlerProcess.localeCompare(b.handlerProcess)
  );
};

const addList = () => {
  visibleEvent.value = true;
  editfromData.value = {
    ownerId: form.data.id,
    ownerType: 3,
    demands: [{ handlerMatters: '', matterAsk: '' }]
  };
};
</script>
<style lang="less" scoped>
.main {
  width: 80%;
  margin: auto;
  .hear {
    width: 70%;
    padding: 20px;
    margin: auto;
    border-radius: 10px;
    margin-bottom: 20px;
    box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.7);
  }
  .business {
    width: 60%;
    margin: auto;
    padding-right: 100px;
  }
}
:deep(.arco-btn) {
  margin-right: 20px;

  width: 120px;
}
.layout {
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    line-height: 50px;
    padding: 0 20px;
    background-color: #f3f8fe;
    border-radius: 4px;
    margin-bottom: 20px;
    div {
      display: flex;
      align-items: center;

      span {
        margin: 0 20px;
        display: inline-block;
        width: 5px;
        height: 30px;
        background-color: #165dff;
      }
    }
  }
  .main {
    padding: 0 40px 20px 40px;
    .cn {
      width: 85%;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .cn-main {
        display: flex;
        width: 45%;
        margin-bottom: 20px;
        align-items: center;
        span {
          width: 100px;
          text-align: end;
          margin-right: 20px;
        }

        .cn-input {
          flex: 1;
        }
      }
    }
  }
  .arco-upload-wrapper {
    flex: 0;
  }
}

footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
.avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 20px;
  p {
    margin: 10px 10px 0 10px;
  }
}
</style>
